package com.wellsoft.pt.app.dingtalk.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

/**
 * Description: 钉钉基本方法工具类
 *  
 * @author Well
 * @date 2020年5月29日
 * @version 1.0
 * 
 * <pre>
 * 修改记录:
 * 修改后版本	修改人		修改日期			修改内容
 * 2020年5月29日.1	Well		2020年5月29日		Create
 * </pre>
 *
 */
public class DingtalkUtils {

	private static Logger logger = LoggerFactory.getLogger(DingtalkUtils.class);

	/**
	 * 个人免密登录场景的签名计算
	 * 
	 * @param timestamp
	 * @param appSecret
	 * @return
	 */
	public static String sign(String timestamp, String appSecret) {
		// 根据timestamp, appSecret计算签名值
		String stringToSign = timestamp;
		try {
			Mac mac = Mac.getInstance("HmacSHA256");
			mac.init(new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256"));
			byte[] signatureBytes = mac.doFinal(stringToSign.getBytes("UTF-8"));
			String signature = new String(Base64.encodeBase64(signatureBytes));
			String urlEncodeSignature = urlEncode(signature);
			return urlEncodeSignature;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "";
	}

	/**
	 * url 编码
	 * 
	 * @param value
	 * @return
	 */
	public static String urlEncode(String value) {
		if (value == null) {
			return "";
		}
		try {
			String encoded = URLEncoder.encode(value, "utf-8"); // encoding参数使用utf-8
			return encoded.replace("+", "%20").replace("*", "%2A").replace("~", "%7E").replace("/", "%2F");
		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException("FailedToEncodeUri", e);
		}
	}

	/**
	 * uri 地址构建，参数替换
	 * 
	 * @param uri
	 * @param args
	 * @return
	 */
	public static String uriFormat(String uri, Object... args) {
		String f = "";
		if (StringUtils.isEmpty(uri))
			return f;
		f = String.format(uri, args);
		return f;
	}

	/**
	 * 转化json字符串
	 * 
	 * @param json
	 *            接口返回json
	 * @return
	 */
	public static JSONObject getJsonResult(String json) {
		JSONObject jb = null;
		if (StringUtils.isNotBlank(json)) {
			jb = JSONObject.fromObject(json);
		}
		if (jb != null) {
			int errcode = jb.getInt("errcode");
			String errorLog = "---------------请求接口失败，错误代码为【%d】,错误信息：%s。-------------------";
			if (errcode == 0) {
				errorLog = "----------------------请求接口成功，返回正确数据！---------------------------";
			} else if (errcode == 88) {
				errorLog = String.format(errorLog, jb.getInt("sub_code"), jb.getString("sub_msg"));
			} else {
				errorLog = String.format(errorLog, jb.getInt("errcode"), jb.getString("errmsg"));
			}
			logger.error(errorLog);
			return jb;
		}
		return null;
	}

	/**
	 * 数据加密密钥。用于回调数据的加密
	 * @param length
	 * @return
	 */
	public static String getAesKey(int length) {
		String aesKey = RandomStringUtils.randomAlphanumeric(length);
		return aesKey;
	}

	public static void main(String[] args) {
		String json = "{\r\n" + "    \"errcode\": 88,\r\n" + "    \"sub_code\": \"60011\",\r\n"
				+ "    \"sub_msg\": \"没有调用该接口的权限\",\r\n"
				+ "    \"errmsg\": \"ding talk error[subcode=60011,submsg=没有调用该接口的权限]\",\r\n"
				+ "    \"request_id\": \"5imjny7u9xwa\"\r\n" + "}";
		JSONObject jb = getJsonResult(json);
		// System.out.println(jb.getString("access_token"));

		String f = String.format("---------------请求接口失败，错误代码为【%d】,错误信息：%s。-------------------", jb.getInt("sub_code"),
				jb.getString("sub_msg"));
		System.out.println(f);
	}
}
